﻿<!DOCTYPE html>
<html>
<head>
    <title>JS Arrays Exercise 6</title>
    <link href="styles/js-console.css" rel="stylesheet" />
</head>
<body>
    <h1>Finds the most frequent number in an array.</h1>
    <label for="arr-input">Array:</label>
    <input type="text" id="arr-input" />
    <button onclick="execute()">Execute</button>
    <div id="js-console"></div>
    <script src="scripts/js-console.js"></script>
    <script>
        function execute()
        {
            var arr_string = jsConsole.read("#arr-input");
            var val = arr_string.split(", ");

            if (val.length > 0)
            {
                // Make array that will store how many times value is present in the val array:
                // val:   4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3
                // count: 1, 1, 2, 2, 1, 1, 3, 4, 3, 2, 5, 1, 2
                var count = new Array(val.length);
                var max_index = 0;

                for (var idx = 0; idx < val.length; idx++)
                {
                    // Cycle all values that haven't been checked so far
                    if (count[idx] == undefined)
                    {
                        var counterValue = 1;
                        var mostIndex = 1;

                        count[idx] = 1;

                        // See how many times val[idx] is present in the array
                        for (var sub_idx = idx + 1; sub_idx < val.length; sub_idx++)
                        {
                            if (val[idx] == val[sub_idx])
                            {
                                // Set value's counter
                                counterValue++;
                                count[sub_idx] = counterValue;
                                mostIndex = sub_idx;
                            }
                        }
                        // Check if current value is present more time in the array than last most frequent number
                        if (count[mostIndex] > count[max_index])
                        {
                            max_index = mostIndex;
                        }
                    }
                }

                // Print the result
                jsConsole.writeLine(val[max_index] + "(" + count[max_index] + " " + ((count[max_index] == 1) ? "time" : "times") + ")");
            }
        }
    </script>
</body>
</html>
